package com.automannn.atm_back.modules.codeGenerator.core.util;


import com.automannn.atm_back.common.system.vo.LoginUser;
import com.automannn.atm_back.modules.codeGenerator.core.pojo.SaveFile;
import com.automannn.atm_back.modules.codeGenerator.core.service.ZipCompressService;
import org.apache.shiro.SecurityUtils;
import org.apache.xmlbeans.impl.common.IOUtil;
import org.jeecgframework.core.util.ApplicationContextUtil;
import sun.misc.IOUtils;

import java.io.*;

/**
 * 文件工具类
 */
public class FileUtils {
    private static volatile FileUtils fileUtils;

    /**
     * 单例模式
     */
    public static FileUtils getInstance() {
        if (fileUtils == null) {
            synchronized (FileUtils.class) {
                if (fileUtils == null) {
                    fileUtils = new FileUtils();
                }
            }
        }
        return fileUtils;
    }

    private FileUtils() {
    }

    /**
     * 读取文件内容（文本文件）
     *
     * @param file 文件对象
     * @return 文件内容
     */
    public String read(File file) {
        throw new RuntimeException("暂不支持!");
    }

    /**
     * 写入文件
     */
    public void write(String code, String path, String fileName) {
        ZipCompressService zipCompressService = (ZipCompressService) ApplicationContextUtil.getContext().getBean("zipCompressService");
        //todo: 将shiro的认证换位springSecurity的授权
        LoginUser loginUser= (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String rootPath = zipCompressService.getTmpDir() +"_"+ loginUser.getUsername();

        if (rootPath.startsWith("/")) rootPath = rootPath.substring(1);
        if (!rootPath.endsWith("/")) rootPath = rootPath + "/";
        path.replaceAll(".", "/");
        path=path+"/";
        File file= new File(rootPath + path);
        if (!file.exists()) file.mkdirs();
        file = new File(rootPath + path + fileName);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(code.getBytes());
            IOUtil.copyCompletely(byteArrayInputStream, fileOutputStream);
        } catch (Exception e) {
            throw new RuntimeException("写入文件出错:" + e.getMessage());
        }
    }

    public static boolean delete(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        }
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isFile()) {
                if (!f.delete()) {
                    return false;
                }
            } else {
                if (!delete(f.getAbsolutePath())) {
                    return false;
                }
            }
        }
        return file.delete();
    }
}
